package archer.framework.security.token.impl;

import archer.framework.security.token.Token;
import archer.framework.security.token.TokenDao;
import archer.framework.security.token.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author christ
 * @date 2016/5/9
 */
public class DefaultTokenManager implements TokenManager {

    private static Logger logger = LoggerFactory.getLogger(DefaultTokenManager.class);

    private TokenDao tokenDao = new MemoryStoreTokenDao();


    @Override
    public Token create(Token token) {
        tokenDao.create(token);
        return token;
    }

    @Override
    public Token update(Token token) {
        if (token != null) {
            tokenDao.update(token);
        }
        return token;
    }

    @Override
    public void touch(String id) {
        Token token = find(id);
        if (token != null) {
            token.touch();
            tokenDao.update(token);
        }
    }

    @Override
    public Token find(String id) {
        Token token = tokenDao.find(id);
        if (token != null && !token.isValidate()) {
            logger.info("TOKEN>>token[" + token.getId() + "] is invalidate , remove it");
            tokenDao.delete(id);
            return null;
        }
        return token;
    }

    @Override
    public void invalidate(String id) {
        tokenDao.delete(id);
    }

    public TokenDao getTokenDao() {
        return tokenDao;
    }

    public DefaultTokenManager setTokenDao(TokenDao tokenDao) {
        this.tokenDao = tokenDao;
        return this;
    }
}
